﻿using Microsoft.AspNetCore.Builder;
using System;
using NetMicro.Core.Helper;
using NetMicro.Core.Ioc.Attributes;
using NetMicro.Swagger.Builders;
using NetMicro.Swagger.Extensions.Options;
using NetMicro.Swagger.Options;

namespace NetMicro.Swagger.Extensions
{
    /// <summary>
    /// Swagger中间件拓展
    /// </summary>
    [SkipScan]
    public static class ApplicationBuilderExtensions
    {
        /// <summary>
        /// 添加Swagger中间件
        /// </summary>
        /// <param name="app"></param>
        /// <param name="routePrefix"></param>
        /// <param name="configure"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseSwaggers(this IApplicationBuilder app, string routePrefix = default, Action<SwaggerConfigureOptions> configure = default)
        {
            var settings = App.GetConfig<SwaggerSettingsOptions>("SwaggerSettings", true);
            // 判断是否启用Swagger
            if (settings.EnableSwagger != true) return app;

            // 载入服务配置选项
            var configureOptions = new SwaggerConfigureOptions();
            configure?.Invoke(configureOptions);

            // 配置 Swagger 全局参数
            app.UseSwagger(options => SwaggerBuilder.Build(options, configureOptions?.SwaggerConfigure));

            // 配置 Swagger UI 参数
            app.UseSwaggerUI(options => SwaggerBuilder.BuildUI(options, routePrefix, configureOptions?.SwaggerUIConfigure));

            // 启用 MiniProfiler组件
            if (settings.EnableMiniProfiler == true) app.UseMiniProfiler();

            return app;
        }
    }
}